package com.jiawa.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.*;
import com.jiawa.train.business.domain.Req.DailyTrainTicketQueryReq;
import com.jiawa.train.business.domain.Req.DailyTrainTicketSaveReq;
import com.jiawa.train.business.domain.resp.DailyTrainTicketQueryResp;
import com.jiawa.train.business.enums.SeatTypeEnum;
import com.jiawa.train.business.enums.TrainTypeEnum;
import com.jiawa.train.business.mapper.DailyTrainTicketMapper;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DailyTrainTicketService {

    @Autowired
    private DailyTrainTicketMapper dailyTrainTicketMapper;
    @Autowired
    private TrainStationService trainStationService;
    @Autowired
    private DailyTrainSeatService dailyTrainSeatService;
    @Resource
    private RedisTemplate<String, PageResp<DailyTrainTicketQueryResp>> redisTemplate;

    @Cacheable(value = "DailyTrainTicketService.queryList")
    public PageResp<DailyTrainTicketQueryResp> queryList(DailyTrainTicketQueryReq req) {



        DailyTrainTicketExample example = new DailyTrainTicketExample();
        List<DailyTrainTicket> trainTickets = dailyTrainTicketMapper.selectByExample(example);
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainTicketQueryResp> dailyTrainTicketQueryResps = BeanUtil.copyToList(trainTickets, DailyTrainTicketQueryResp.class);
        PageInfo<DailyTrainTicketQueryResp> pageInfo = new PageInfo<>(dailyTrainTicketQueryResps);

        PageResp<DailyTrainTicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(dailyTrainTicketQueryResps);
        return pageResp;
    }


    public void save(DailyTrainTicketSaveReq req) {
        DailyTrainTicket dailyTrainTicket = new DailyTrainTicket();
        BeanUtil.copyProperties(req,dailyTrainTicket);
        if(ObjectUtil.isNull(req.getId())){
            dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainTicket.setUpdateTime(new Date());
            dailyTrainTicket.setCreateTime(new Date());
            dailyTrainTicketMapper.insert(dailyTrainTicket);
        }else {
            dailyTrainTicket.setUpdateTime(new Date());
            dailyTrainTicketMapper.updateByPrimaryKeySelective(dailyTrainTicket);
        }
    }

    public void delete(Long id) {
        dailyTrainTicketMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public void genDaily( DailyTrain dailyTrain,Date date,String trainCode){
        //删除某日某次的车站信息
        DailyTrainTicketExample ticketExample = new DailyTrainTicketExample();
        ticketExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);
        dailyTrainTicketMapper.deleteByExample(ticketExample);

        //查询途径的车站信息

        List<TrainStation> stationList = trainStationService.selectByTrainCode(trainCode);
        if(CollUtil.isEmpty(stationList)){
            return;
        }

       for(int i=0;i<stationList.size();i++){
           //得到出发站
           TrainStation trainStationStart = stationList.get(i);
           for(int j=i+1;j<stationList.size();j++){
               TrainStation trainStationEnd = stationList.get(j);
               BigDecimal sumKM= BigDecimal.ZERO;

               DailyTrainTicket dailyTrainTicket = new DailyTrainTicket();
               dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
               dailyTrainTicket.setUpdateTime(new Date());
               dailyTrainTicket.setCreateTime(new Date());
               dailyTrainTicket.setDate(date);
               dailyTrainTicket.setTrainCode(trainCode);
               dailyTrainTicket.setStart(trainStationStart.getName());
               dailyTrainTicket.setEnd(trainStationEnd.getName());
               dailyTrainTicket.setStartPinyin(trainStationStart.getNamePinyin());
               dailyTrainTicket.setEndPinyin(trainStationEnd.getNamePinyin());
               dailyTrainTicket.setStartIndex(trainStationStart.getIndex());
               dailyTrainTicket.setEndIndex(trainStationEnd.getIndex());
               dailyTrainTicket.setEndTime(trainStationEnd.getInTime());
               dailyTrainTicket.setStartTime(trainStationStart.getOutTime());
               int ydz =dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.YDZ.getCode());
               int edz =dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.EDZ.getCode());
               int yw = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.YW.getCode());
               int rw = dailyTrainSeatService.countSeat(date, trainCode, SeatTypeEnum.RW.getCode());

               String type = dailyTrain.getType();
               BigDecimal priceRate = EnumUtil.getFieldBy(TrainTypeEnum::getPriceRate, TrainTypeEnum::getCode, type);
               BigDecimal ydzPrice = sumKM.multiply(SeatTypeEnum.YDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
               BigDecimal edzPrice = sumKM.multiply(SeatTypeEnum.EDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
               BigDecimal rwPrice = sumKM.multiply(SeatTypeEnum.RW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
               BigDecimal ywPrice = sumKM.multiply(SeatTypeEnum.YW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
               dailyTrainTicket.setYdz(ydz);
               dailyTrainTicket.setYdzPrice(ydzPrice);
               dailyTrainTicket.setEdz(edz);
               dailyTrainTicket.setEdzPrice(edzPrice);
               dailyTrainTicket.setRw(rw);
               dailyTrainTicket.setRwPrice(rwPrice);
               dailyTrainTicket.setYw(yw);
               dailyTrainTicket.setYwPrice(ywPrice);
               dailyTrainTicketMapper.insert(dailyTrainTicket);
           }
       }
    }


    public DailyTrainTicket selectByUnique(String trainCode,Date date, String start,String end){
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andStartEqualTo(start)
                .andEndEqualTo(end);

        List<DailyTrainTicket> ticketList = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);

        if(CollUtil.isNotEmpty(ticketList)){
            return ticketList.get(0);
        }else {
            return null;
        }
    }

}
